import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入nprogress相关的js和css文件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  // @别名：代表src目录的绝对路径名地址
  { path: '/login', name: 'login', component: () => import('@/views/login') },
  { path: '/', redirect: '/welcome' },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home'),
    redirect: '/welcome', // 重定向
    children: [
      { path: '/welcome', name: 'welcome', component: () => import('@/views/welcome') },
      { path: '/fans', name: 'fans', component: () => import('@/views/fans/fans.vue') },
      { path: '/material', name: 'material', component: () => import('@/views/material/material.vue') },
      { path: '/account', name: 'account', component: () => import('@/views/account/account.vue') },
      { path: '/articleedit/:aid', name: 'articleedit', component: () => import('@/views/articleedit/articleedit.vue') },
      { path: '/article', name: 'article', component: () => import('@/views/article') },
      { path: '/articleadd', name: 'articleadd', component: () => import('@/views/articleadd/articleadd.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 开始进度条表演
  NProgress.start()
  // 非登录用户，禁止访问后台页面，相反强制登录
  // 用户没有登录系统，userinfo===null
  let userinfo = window.sessionStorage.getItem('userinfo')
  if (!userinfo && to.path !== '/login') {
    return next('/login')
  }

  next() // 放行
})

// 路由后置守卫
router.afterEach((to, from) => {
  // 结束进度条表演
  NProgress.done()
})

export default router
